<?php
session_start();
// 权限验证
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 验证文章ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: article.php?error=无效的文章ID');
    exit;
}
$id = (int)$_GET['id'];

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 先查询封面图路径
    $stmt = $pdo->prepare("SELECT cover_img FROM article WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $article = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$article) {
        header('Location: article.php?error=文章不存在或已被删除');
        exit;
    }

    // 删除文章记录
    $stmt = $pdo->prepare("DELETE FROM article WHERE id = :id");
    $stmt->execute([':id' => $id]);

    // 删除封面图片
    if (!empty($article['cover_img']) && file_exists($article['cover_img'])) {
        unlink($article['cover_img']);
    }

    header('Location: article.php?success=文章删除成功');
    exit;

} catch (PDOException $e) {
    header('Location: article.php?error=删除失败：' . $e->getMessage());
    exit;
}